const fs = require('fs');
const path = require('path');
const WEB3 = require('web3');
const HDWalletProvider = require('truffle-hdwallet-provider');

const contractPath = path.resolve(__dirname, '../src/compiled/WalletList.json');
const WalletListContract = require(contractPath);
const abi = WalletListContract.abi;
const bytecode = '0x' + WalletListContract.evm.bytecode.object;

// const provider = new HDWalletProvider(
//   "empower fancy first raise item market inch exchange pilot glass future flash",
//   "https://ropsten.infura.io/v3/67efbafa445847bb83b7b469f1800092"
// );
// const web3 = new WEB3(provider);
const web3 = new WEB3("http://127.0.0.1:7545");

(async () => {
  console.log("自执行");
  const accounts = await web3.eth.getAccounts();
  console.log('合约部署的账号：', accounts);
  console.time('Contract deploy consume time');
  const result = await new web3.eth.Contract(abi).deploy({
    data: bytecode
  }).send({
    from: accounts[0],
    gas: 4612388
  });
  console.timeEnd('Contract deploy consume time');
  const contractAddress = result.options.address;
  console.log('Contract Deploy Success: ', contractAddress);
  console.log('Click to see contract: ', `https://ropsten.etherscan.io/address/${contractAddress}`);

  const addressFile = path.resolve(__dirname, '../src/address.js');
  fs.writeFileSync(addressFile, "export default " + JSON.stringify(contractAddress));
  console.log('地址写入成功: ', addressFile);
})();